<template>
	<u-upload 
	ref="upload"
	:action="action"
	:max-size="5 * 1024 * 1024" 
	max-count="1"
	:multiple='false'
	:deletable='false'
	:before-upload="beforeUpload"
	:custom-btn="true"
	:form-data='formDate'
	show-progress='false'
	@on-success='onSuccess'
	width="0"
	height="0"
	>
		<u-avatar slot='addBtn' :src="vuex_user.avatar_url" size="140"></u-avatar>
	</u-upload>
</template>

<script>
	let _this = {}
	export default {
		data() {
			return {
				upFileName:'',
				formDate:{},
				action: 'http:/laravel_shop_api.luwnto.oss-cn-beijing.aliyuncs.com/',
			};
		},
		created() {
			_this = this
		}
		,methods:{
			/**
			 * 上传成功之后
			 */
			async onSuccess(){
				//移出预览区域图片
				this.$refs.upload.remove(0)
				console.log(this.upFileName);
				//请求api更新图像
				await this.$u.api.userAvatar({avatar: this.upFileName})
				//更新缓存的用户信息
				this.$u.utils.upadtaUser()
				this.$u.toast('更新头像成功！')
			},
			/** 上传前的钩子函数
			* 注意：在小程序中this 可能会丢失，需要创建
			* let _this 
			* created(){
			* _this = this
			* }
			 * @param {Object} index 索引
			 * @param {Object} list 列表
			 */
			async beforeUpload(index, list) {
				const {file} = list[0]
				// #ifdef H5
				const fileName = file.name
				// #endif
				
				// #ifndef H5
				const fileName = file.path
				// #endif
				
				
				// 只上传偶数索引的文件
				//请求api，获取token
				const oss= await _this.$u.api.authOssToken()
				// console.log(oss);
				//设置上传域名
				_this.action = oss.host
				//处理唯一文件名
				const suffix = fileName.slice(fileName.lastIndexOf('.'))
				// console.log(suffix);
				const upFileName = _this.$u.guid(20) +suffix
				// console.log(upFileName);
				_this.upFileName = upFileName
				//额外的参数
				_this.formDate={
					 'key' : upFileName,//上传后的文件名
					'policy': oss.policy,
					'OSSAccessKeyId': oss.accessid, 
					'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
					'signature': oss.signature,
				}
				if(index % 2 == 0) return true;
				else return false;
			}
		}
	}
</script>

<style>

</style>
